package cn.cdutetc.library.controller;

import cn.cdutetc.library.entity.dto.UserCreateDTO;
import cn.cdutetc.library.entity.dto.UserLoginDTO;
import cn.cdutetc.library.entity.dto.UserUpdateDTO;
import cn.cdutetc.library.entity.dto.UserVO;
import cn.cdutetc.library.entity.dto.LoginResponseDTO;
import cn.cdutetc.library.common.ApiResponse;
import cn.cdutetc.library.service.UserService;
import cn.cdutetc.library.service.SystemLogService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户管理相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SystemLogService systemLogService;

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录接口")
    public ApiResponse<LoginResponseDTO> login(@RequestBody @Valid UserLoginDTO loginDTO, HttpServletRequest request) {
        try {
            // 调用用户服务执行登录逻辑，获取登录响应
            LoginResponseDTO loginResponse = userService.login(loginDTO);

            // 记录登录成功日志
            // 注意：如果需要用户真实姓名等信息，可以从登录响应中获取
            systemLogService.recordLoginLog(
                    loginDTO.getUsername(),
                    loginDTO.getUsername(),  // 这里可以替换为实际的用户名或昵称
                    request.getRemoteAddr(),
                    request.getHeader("User-Agent"),
                    true,
                    null
            );

            return ApiResponse.success(loginResponse);
        } catch (Exception e) {
            // 记录登录失败日志
            systemLogService.recordLoginLog(
                    loginDTO.getUsername(),
                    loginDTO.getUsername(),  // 这里可以替换为实际的用户名或昵称
                    request.getRemoteAddr(),
                    request.getHeader("User-Agent"),
                    false,
                    e.getMessage()
            );
            throw e;
        }
    }
    @PostMapping
    @Operation(summary = "创建用户", description = "创建新用户")
    public ApiResponse<Integer> createUser(@RequestBody @Valid UserCreateDTO createDTO) {
        Integer userId = userService.createUser(createDTO);
        return ApiResponse.success(userId);
    }

    @PutMapping
    @Operation(summary = "更新用户", description = "更新用户信息")
    public ApiResponse<Boolean> updateUser(@RequestBody @Valid UserUpdateDTO updateDTO) {
        System.out.println("接收到更新用户请求，DTO: " + updateDTO);
        boolean result = userService.updateUser(updateDTO);
        return ApiResponse.success(result);
    }

    @DeleteMapping("/{userId}")
    @Operation(summary = "删除用户", description = "根据ID删除用户")
    public ApiResponse<Boolean> deleteUser(@PathVariable Integer userId) {
        boolean result = userService.deleteUser(userId);
        return ApiResponse.success(result);
    }

    @GetMapping("/{userId}")
    @Operation(summary = "获取用户详情", description = "根据ID获取用户详情")
    public ApiResponse<UserVO> getUserById(@PathVariable Integer userId) {
        UserVO userVO = userService.getUserById(userId);
        return ApiResponse.success(userVO);
    }

    @GetMapping("/page")
    @Operation(summary = "分页查询用户", description = "分页查询用户列表")
    public ApiResponse<IPage<UserVO>> pageUsers(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "关键字") @RequestParam(required = false) String keyword,
            @Parameter(description = "角色筛选") @RequestParam(required = false) String role,
            @Parameter(description = "状态筛选") @RequestParam(required = false) String status) {
        IPage<UserVO> result = userService.pageUsers(page, size, keyword, role, status);
        return ApiResponse.success(result);
    }

    @PutMapping("/password")
    @Operation(summary = "修改密码", description = "修改用户密码")
    public ApiResponse<Boolean> changePassword(
            @Parameter(description = "用户ID") @RequestParam Integer userId,
            @Parameter(description = "旧密码") @RequestParam String oldPassword,
            @Parameter(description = "新密码") @RequestParam String newPassword) {
        boolean result = userService.changePassword(userId, oldPassword, newPassword);
        return ApiResponse.success(result);
    }

    @PutMapping("/reset-password/{userId}")
    @Operation(summary = "重置密码", description = "重置用户密码")
    public ApiResponse<String> resetPassword(@PathVariable Integer userId) {
        String newPassword = userService.resetPassword(userId);
        return ApiResponse.success(newPassword);
    }

    @GetMapping("/export")
    @Operation(summary = "导出用户数据", description = "导出用户数据到Excel文件")
    public void exportUsers(
            HttpServletResponse response,
            @Parameter(description = "搜索关键字") @RequestParam(required = false) String keyword) {
        try {
            userService.exportUsers(response, keyword);
        } catch (Exception e) {
            throw new RuntimeException("导出用户数据失败: " + e.getMessage());
        }
    }

    @GetMapping("/import-template")
    @Operation(summary = "下载导入模板", description = "下载用户导入Excel模板")
    public void downloadImportTemplate(HttpServletResponse response) {
        try {
            userService.downloadImportTemplate(response);
        } catch (Exception e) {
            throw new RuntimeException("下载导入模板失败: " + e.getMessage());
        }
    }

    @PostMapping("/import")
    @Operation(summary = "导入用户数据", description = "从Excel文件导入用户数据")
    public ApiResponse<String> importUsers(
            @Parameter(description = "Excel文件") @RequestParam("file") MultipartFile file) {
        String result = userService.importUsers(file);
        return ApiResponse.success(result);
    }

    @GetMapping("/readers/page")
    @Operation(summary = "分页查询读者", description = "分页查询读者列表（角色为normal_user的用户）")
    public ApiResponse<IPage<UserVO>> pageReaders(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "关键字") @RequestParam(required = false) String keyword) {
        IPage<UserVO> result = userService.pageReaders(page, size, keyword);
        return ApiResponse.success(result);
    }

    @GetMapping("/readers/all")
    @Operation(summary = "获取所有读者", description = "获取所有读者列表（角色为normal_user的用户）")
    public ApiResponse<List<UserVO>> getAllReaders(
            @Parameter(description = "关键字") @RequestParam(required = false) String keyword) {
        List<UserVO> result = userService.getAllReaders(keyword);
        return ApiResponse.success(result);
    }

    @GetMapping("/readers/export")
    @Operation(summary = "导出读者数据", description = "导出读者数据到Excel文件（仅导出normal_user角色用户）")
    public void exportReaders(
            HttpServletResponse response,
            @Parameter(description = "搜索关键字") @RequestParam(required = false) String keyword) {
        try {
            userService.exportReaders(response, keyword);
        } catch (Exception e) {
            throw new RuntimeException("导出读者数据失败: " + e.getMessage());
        }
    }
}